package com.woniuxy.classteacher.service.impl;

import com.woniuxy.classteacher.cofiguration.FileUploadProperties;
import com.woniuxy.classteacher.mapper.*;
import com.woniuxy.classteacher.repository.VideoRepository;
import com.woniuxy.classteacher.service.VideoService;
import com.woniuxy.classteacher.uitility.EsUtil;
import com.woniuxy.classteacher.uitility.TimeUtil;
import com.woniuxy.commons.entity.SchoolInfo;
import com.woniuxy.commons.entity.SchoolLeader;
import com.woniuxy.commons.entity.StudentInfo;
import com.woniuxy.commons.entity.Vedio;
import com.woniuxy.commons.entity.wyh.TeacherInfo;
import com.woniuxy.commons.entity.wyh.TeamInfo;
import com.woniuxy.commons.exception.NoAuthorityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.codec.AbstractDataBufferDecoder;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @author 李英勇
 * @date 2020/7/21 - 17:34
 */
@Service
public class VideoServiceImpl implements VideoService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;    //用于操作es
    @Autowired
    private EsUtil esUtil;
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private PrincipalMapper principalMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassTeacherMapper classTeacherMapper;
    @Autowired
    private VideoRemarkMapper videoRemarkMapper;

    @Autowired
    private FileUploadProperties fileUploadProperties;

    /**
    * @Author: 李英勇
    * @Description: 上传视频
    * @DateTime: 2020/8/5 16:36
    * @Params: [vedio, refreshToken]
    * @Return int
    */
    @Override
    @Transactional
    public int upVideo(Vedio vedio, String refreshToken) {
        //设置视频为未审核 0代表未审核 1代表审核
        vedio.setExamine(0);
        //判断索引是否已经存在
        boolean es = esUtil.isExistsIndex("es");
        if (!es) {
            //将视频创建索引加入es
            elasticsearchTemplate.createIndex(Vedio.class);

            //配置映射
            elasticsearchTemplate.putMapping(Vedio.class);
        }

        //在redis中获取用户的rid
        //通过refreshToken获取数据
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshToken);
        //获取rid
        int rid = (int) data.get("rid");
        //设置用户id
        vedio.setTeacherid(rid);
        //设置上传时间
        vedio.setDate(TimeUtil.getNow());
        //设置学校
        TeacherInfo teacherInfo = classTeacherMapper.findTeacherInfoByTcid(rid);
        vedio.setSchool(teacherInfo.getSchoolInfo().getSname());
        //加入数据库
        videoMapper.upVideo(vedio);
        //获取最新的id
        int maxVid = videoMapper.getMaxVid();
        vedio.setVid(maxVid);
        //将vido加入es
        videoRepository.save(vedio);

        return 1;
    }

    /**
    * @Author: 李英勇
    * @Description: 通过视频id查询视频，并对视频访问者的身份进行权限验证
    * @DateTime: 2020/8/5 16:37
    * @Params: [vid, refreshToken]
    * @Return com.woniuxy.commons.entity.Vedio
    */
    @Override
    @Transactional
    public Vedio getVideoByVid(int vid, String refreshToken) {
        System.out.println(vid + "====================" + refreshToken);
        Vedio video = videoMapper.getVideoByVid(vid);
        //获取视频的访问等级
        int open = video.getOpen();
        //获取视频的上传学校班级
        String school = video.getSchool();
        TeacherInfo teacher = classTeacherMapper.findTeacherInfoByTcid(video.getTeacherid());
        List<TeamInfo> teamInfos = teacher.getTeamInfos();//班级


        //在redis中获取用户的role和rid
        //通过refreshToken获取数据
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshToken);
        //获取role
        String role = (String) data.get("role");
        //获取rid
        int rid = (int) data.get("rid");


        //判断访问等级
        if (open == 0) {
            //全市公开
            //刷新es
            video = refreshEs(vid);
            //返回
            return video;
        } else if (open == 1) {
            //全校公开

            //判断角色
            if (role.equals("student")) {
                //获取学生信息
                StudentInfo stu = studentMapper.findStuByStuid(rid);
                //获取学生的学校
                SchoolInfo schoolInfo = stu.getSchoolInfo();
                //判断学校是否一致
                if (schoolInfo.getSname().equals(school)) {
                    //刷新es
                    video = refreshEs(vid);
                    //返回
                    return video;
                } else {
                    throw new NoAuthorityException("你没有权限访问");
                }

            } else if (role.equals("principal")) {
                //获取校长
                SchoolLeader schoolLeader = principalMapper.findSchoolLeaderByLid(rid);
                //获取学校
                SchoolInfo schoolInfo = schoolLeader.getSchoolInfo();
                //判断学校是否一致
                if (schoolInfo.getSname().equals(school)) {
                    //刷新es
                    video = refreshEs(vid);
                    //返回
                    return video;
                } else {
                    throw new NoAuthorityException("你没有权限访问");
                }

            } else if (role.equals("teacher")) {
                //获取老师
                TeacherInfo teacherInfo = classTeacherMapper.findTeacherInfoByTcid(rid);
                //获取学校
                SchoolInfo schoolInfo = teacherInfo.getSchoolInfo();
                //判断学校是否一致
                if (schoolInfo.getSname().equals(school)) {
                    //刷新es
                    video = refreshEs(vid);
                    //返回
                    return video;
                } else {
                    throw new NoAuthorityException("你没有权限访问");
                }
            }

        } else if (open == 2) {
            //判断角色
            if (role.equals("student")) {
                //获取学生
                StudentInfo stu = studentMapper.findStuByStuid(rid);
                //获取学校
                SchoolInfo schoolInfo = stu.getSchoolInfo();
                //获取班级
                TeamInfo classInfo = stu.getTeamInfo();

                //判断学校班级是否一致
                if (schoolInfo.getSname().equals(school) && teamInfos.contains(classInfo)) {

                    video = refreshEs(vid);
                    //返回
                    return video;
                } else {
                    throw new NoAuthorityException("你没有权限访问");
                }

            } else if (role.equals("principal")) {
                //获取校长
                SchoolLeader schoolLeader = principalMapper.findSchoolLeaderByLid(rid);
                //获取学校
                SchoolInfo schoolInfo = schoolLeader.getSchoolInfo();
                //判断学校是否一致
                if (schoolInfo.getSname().equals(school)) {
                    //刷新es
                    video = refreshEs(vid);
                    //返回
                    return video;
                } else {
                    throw new NoAuthorityException("你没有权限访问");
                }

            } else if (role.equals("teacher")) {
                //获取老师
                TeacherInfo teacherInfo = classTeacherMapper.findTeacherInfoByTcid(rid);
                //获取学校
                SchoolInfo schoolInfo = teacherInfo.getSchoolInfo();
                //判断学校是否一致
                if (schoolInfo.getSname().equals(school)) {
                    //刷新es
                    video = refreshEs(vid);
                    //返回
                    return video;
                } else {
                    throw new NoAuthorityException("你没有权限访问");
                }
            }

        }
        return null;
    }

    private Vedio refreshEs(int vid) {
        Vedio video;
        videoMapper.viewsVideoByVid(vid);
        //获取video
        video = videoMapper.getVideoByVid(vid);
        //更新es
        videoRepository.save(video);
        return video;
    }

    /**
    * @Author: 李英勇
    * @Description: 视频点赞
    * @DateTime: 2020/8/5 16:38
    * @Params: [vid]
    * @Return int
    */
    @Override
    @Transactional
    public int thumbsupVideoByVid(int vid) {
        //点赞
        videoMapper.thumbsupVideoByVid(vid);
        //更新es
        this.refreshEs(vid);

        return 1;
    }
    /**
    * @Author: 李英勇
    * @Description: 修改视频的知识点和描述
    * @DateTime: 2020/8/5 16:38
    * @Params: [vedio]
    * @Return int
    */
    @Override
    public int updateVideo(Vedio vedio) {
        //更新视频
        videoMapper.updateVideo(vedio);
        //更新es
        this.refreshEs(vedio.getVid());
        return 1;
    }
    /**
    * @Author: 李英勇
    * @Description: 删除视频
    * @DateTime: 2020/8/5 16:41
    * @Params: [vid]
    * @Return int
    */
    @Override
    @Transactional
    public int delVideoByVid(int vid) {
        //获取视频路径
        Vedio video = videoMapper.getVideoByVid(vid);
        //删除es中的数据
        videoRepository.delete(video);
        //删除视频
        videoMapper.delVideoByVid(vid);
        //删除评论
        videoRemarkMapper.delRemarkByVid(vid);
        //删除视频在磁盘的数据

        //获取路径
        String path = video.getPath();
        String delFolder = fileUploadProperties.getDelFolder();
        //拼接路径
        File file = new File(delFolder + File.separator + path);
        System.out.println(file);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
        return 1;
    }

}
